﻿using JESAI.EventBus.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace JESAI.EventBus.EventBusStores
{
    internal sealed partial class ChannelEventStore : IEventStore
    {
        /// <summary>
        /// 内存通道事件源存储器
        /// </summary>
        private readonly Channel<IEvent> _channel;

        public ChannelEventStore(int capacity, BoundedChannelFullMode fullMode = BoundedChannelFullMode.Wait)
        {
            //创建消息上限通道
            _channel = Channel.CreateBounded<IEvent>(new BoundedChannelOptions(capacity)
            {
                FullMode = fullMode
            });
        }


        public async ValueTask<IEvent> Pop(CancellationToken cancellationToken)
        {
            var @event = await _channel.Reader.ReadAsync(cancellationToken);
            return @event;
        }

        public async ValueTask Push(IEvent @event, CancellationToken cancellationToken)
        {
            if (@event == null)
            {
                throw new ArgumentNullException(nameof(@event));
            }

            await _channel.Writer.WriteAsync(@event, cancellationToken);
        }
    }
}
